from django.http import JsonResponse
import copy
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
# from django.contrib.auth import login as _login, logout
from django.views.decorators.csrf import csrf_exempt
from .login_utils import get_login_user, set_logout, is_login, set_login

# json返回结果的默认结构
JSONResult = dict(result=0, data=[], message="")


@csrf_exempt
def create_user(request):
    """
    注册用户
    :return:
    """
    result = copy.deepcopy(JSONResult)
    username = request.POST.get('username', '').strip()
    password = request.POST.get('password', '')
    if not username or not password:
        result['message'] = "用户名或密码不能为空"
    elif len(username) < 6 or len(password) < 6:
        result['result'] = -2
        result['message'] = "用户名或密码长度不能少于6位"
    else:
        if User.objects.filter(username=username).count() > 0:
            result['result'] = -3
            result['message'] = "用户名已被注册"
        else:
            user = User.objects.create_user(username=username, password=password)
            if user:
                result['result'] = 1
                result['message'] = '注册成功,请登录'
            else:
                result['message'] = "注册失败。请重试"
    return JsonResponse(result)


@csrf_exempt
def login_user(request):
    """
    登录
    :return:
    """
    # print([(k, v) for k, v in request.META.items()])
    result = copy.deepcopy(JSONResult)
    username = request.POST.get('username', '').strip()
    password = request.POST.get('password', '')
    if not username or not password:
        result['result'] = -1
        result['message'] = "用户名或密码不能为空"
    else:
        user = authenticate(username=username, password=password)
        if user:
            result['result'] = 1
            result['message'] = '登录成功'
            result['token'] = set_login(request, user)
            # for k, v in request.session.items():
            #     print(k + "=" + v)
            # print(dir(request.session))
            # print()
            # print(user.get_session_auth_hash())
            # # 登录用户的id
            # print(request.session.get('_auth_user_id'))
        else:
            result['message'] = '用户或密码错误'
    return JsonResponse(result)


@csrf_exempt
def logout_user(request):
    """
    退出登录
    :param request:
    :return:
    """
    result = copy.deepcopy(JSONResult)
    token = request.POST.get('token', '')
    if not token:
        result['message'] = "未传递有效的token，不可访问"
    else:
        set_logout(request, token)
        result['result'] = 1
        result['message'] = '退出登录成功'
    return JsonResponse(result)


@csrf_exempt
def query_user(request):
    """
    查询用户信息
    :return:
    """
    result = copy.deepcopy(JSONResult)
    username = request.GET.get("username")
    if not username:
        result['result'] = -1
        result['message'] = "请输入用户名"
    elif request.user.is_authenticated:
        user = User.objects.get(username=username)
        if not user:
            result['result'] = -2
            result['message'] = "此用户不存在"
        else:
            result['result'] = 1
            result['user'] = dict(username=username, join_time=user.date_joined)
    else:
        result['result'] = -1
        result['message'] = "未登录，不可访问"
    return JsonResponse(result)
